package com.hyjiacan.h2c.commands

import com.hyjiacan.h2c.Cmd
import com.hyjiacan.h2c.H2
import com.hyjiacan.h2c.SqlResolver
import java.io.File

class CommandRunFile : ICommand {
    override val name: String
        get() = "file"
    override val description: String
        get() = "运行一个 SQL 文件。例: file /path/to/file.sql"

    override fun test(string: String): Boolean {
        return string.startsWith(name)
    }

    override fun run(string: String, db: H2): Boolean {
        val filename = string.substring(name.length).trim()

        if (filename == "") {
            Cmd.pl("请指定文件名，例")
            Cmd.pl("file /path/to/file.sql")
            return true
        }

        val file = File(filename)
        Cmd.pl("正在执行文件 ${file.absolutePath} ...")
        if (!file.exists()) {
            Cmd.pl("文件不存在")
            return true
        }

        SqlResolver(file).use { resolver ->
            run wrapper@{
                resolver.forEach {
                    Cmd.pl("正在执行\n$it")
                    val result = db.execute(it)
                    Cmd.pl("执行完成")
                    Cmd.printResult(result)
                    if (!result.success) {
                        return@wrapper
                    }
                }
            }
        }
        return true
    }
}